package com.useeinfo.oa.modules.inspection.biz;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.useeinfo.framework.extend.biz.CrudBiz;
import com.useeinfo.framework.sugar.tools.StringConverters;
import com.useeinfo.oa.common.utils.ResultUtil.ResultDto;
import com.useeinfo.oa.common.utils.ResultUtil.ResultUtil;
import com.useeinfo.oa.modules.base.biz.DictInfoBiz;
import com.useeinfo.oa.modules.base.biz.PositionBiz;
import com.useeinfo.oa.modules.base.entity.Organization;
import com.useeinfo.oa.modules.inspection.dao.InsApplyOrderDao;
import com.useeinfo.oa.modules.inspection.entity.InsApplyOrder;
import com.useeinfo.oa.modules.inspection.entity.InspectionOrder;
import com.useeinfo.oa.modules.inspection.enums.InsApplyTypeEnum;
import com.useeinfo.oa.modules.inspection.enums.InsOrderOperationEnum;
import com.useeinfo.oa.modules.inspection.enums.InsOrderStatusEnum;
import com.useeinfo.oa.modules.maintaining.biz.MaintainOrderLogBiz;
import com.useeinfo.oa.modules.maintaining.enums.OrderOperationEnum;
import com.useeinfo.oa.modules.security.biz.OrganizationBiz;
import com.useeinfo.oa.modules.security.biz.SystemUserBiz;
import com.useeinfo.oa.modules.security.entity.SystemUser;
import com.useeinfo.oa.modules.security.util.SessionKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Service
public class InsApplyOrderBiz extends CrudBiz<InsApplyOrderDao, InsApplyOrder> {

    @Autowired
    private InspectionOrderBiz inspectionOrderBiz;
    @Autowired
    private InspectionOrderLogBiz inspectionOrderLogBiz;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private OrganizationBiz organizationBiz;
    @Autowired
    private SystemUserBiz systemUserBiz;
    @Autowired
    private PositionBiz positionBiz;
    @Autowired
    private DictInfoBiz dictInfoBiz;

    /**
     * 保存用户对工单的延期或取消申请
     *
     * @param orderId   工单ID
     * @param delayTime 延期时间
     * @param type      类型 cancel取消 delay延期
     * @param reason    原因
     * @return
     */
    public ResultDto saveOrUpdate(String orderId, String delayTime, String type, String reason,String dictInfoId) {
        SystemUser systemUser = SessionKeyUtils.getSessionUser(request);
        if (null == systemUser) {
            return ResultUtil.error("用户信息有误，未登录");
        }
        InspectionOrder inspectionOrder = inspectionOrderBiz.findModel(StringConverters.null2Long(orderId));
        if (null == inspectionOrder) {
            return ResultUtil.error("工单信息有误");
        }
        if (!inspectionOrder.getOrderStatusEnum().getCode().equals("WAIT_PRESENCE") && !inspectionOrder.getOrderStatusEnum().getCode().equals("UNFINISHED")) {
            return ResultUtil.error("工单现有状态不可提交申请");
        }

        if (inspectionOrder.getDelay()) {
            return ResultUtil.error("该工单正在延期审核中，不可再次提交新的审核");
        }
        if (inspectionOrder.getCancel()) {
            return ResultUtil.error("该工单正在取消审核中，不可再次提交新的审核");
        }
        if (inspectionOrder.isAuditing()) {
            return ResultUtil.error("该工单正在完成审核中，不可再次提交新的审核");
        }
        Date delayDate = StringConverters.formatDate(delayTime, "yyyy-MM-dd HH:mm");
        if (Boolean.valueOf(StringConverters.null2String(type).equals("cancel"))) {
            //取消工单
            if (null == inspectionOrder.getCancelFlowID()) {
                //没有审批流  工单直接取消
                inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.CANCEL);
            } else {
                JSONArray cancelFlow;
                try {
                    cancelFlow = JSONArray.parseArray(inspectionOrder.getCancelFlow());
                } catch (Exception e) {
                    return ResultUtil.error("该工单取消流有问题，请联系相应负责人");
                }

                if (null != cancelFlow && cancelFlow.size() > 0) {//配置了审批流  但没有配置节点  直接通过
                    inspectionOrder.setCancel(true);//标志工单处于取消审核中
                    JSONObject jsonObject = (JSONObject) cancelFlow.get(0);
                    Organization organization = organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId")));
                    inspectionOrder.setLevel(1);
                    inspectionOrder.setOrganization(organization);
                    if (cancelFlow.size() == 1) {
                        inspectionOrder.setAuditLast(true);
                    } else {
                        inspectionOrder.setAuditFirst(true);
                    }
                    String auditType = jsonObject.getString("nodeTypeEnum");
                    if (StringConverters.null2String(auditType).equals("USER")) {
                        inspectionOrder.setAuditSystemUser(systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                    } else {
                        inspectionOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                    }
                }else{
                    inspectionOrder.setOrderStatusEnum(InsOrderStatusEnum.CANCEL);

                }
            }
            //操作日志
            inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.CANCEL_ORDER, request);
        } else if (Boolean.valueOf(StringConverters.null2String(type).equals("delay"))) {//申请延期

            if (null == delayDate) {
                return ResultUtil.error("请传入正确的延期时间");
            }
            if(!delayDate.after(inspectionOrder.getDelayRealTime())){
                return ResultUtil.error("延期时间早于结束时间和上次延期时间");
            }
            inspectionOrder.setDelayTime(delayDate);
            if (null == inspectionOrder.getDelayFlowID()) { //没有配置审批流  直接通过
                inspectionOrder.setDelayRealTime(delayDate);
            } else { // 配置了审批流

                JSONArray delayFlow;
                try {
                    delayFlow = JSONArray.parseArray(inspectionOrder.getDelayFlow());
                } catch (Exception e) {
                    return ResultUtil.error("该工单延期审批流有问题，请联系相应负责人");
                }

                if (null == delayFlow || delayFlow.size() <= 0) {//配置了审批流  但没有配置节点  直接通过
                    inspectionOrder.setDelayRealTime(delayDate);
                } else {
                    inspectionOrder.setDelay(true); //标志工单处于延期审核中
                    JSONObject jsonObject = (JSONObject) delayFlow.get(0);
                    Organization organization = organizationBiz.findModel(StringConverters.null2Long(jsonObject.getString("organizationId")));
                    inspectionOrder.setLevel(1);
                    inspectionOrder.setOrganization(organization);
                    if (delayFlow.size() == 1) {
                        inspectionOrder.setAuditLast(true);
                    } else {
                        inspectionOrder.setAuditFirst(true);
                    }
                    String auditType = jsonObject.getString("nodeTypeEnum");
                    if (StringConverters.null2String(auditType).equals("USER")) {
                        inspectionOrder.setAuditSystemUser(systemUserBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));
                    } else {
                        inspectionOrder.setPosition(positionBiz.findModel(StringConverters.null2Long(jsonObject.getString("relationId"))));

                    }
                }

            }
            //操作日志
            inspectionOrderLogBiz.saveInspectionOrderLog(inspectionOrder, InsOrderOperationEnum.DELAY_ORDER, request);
        }


        /****创建申请记录*****/
        InsApplyOrder insapplyOrder = new InsApplyOrder();
        insapplyOrder.setCreateDate(new Date());
        insapplyOrder.setApplyDate(new Date());
        if (StringConverters.null2String(type).equals("cancel")) {
            insapplyOrder.setDelayDate(delayDate);
            insapplyOrder.setInsapplyTypeEnum(InsApplyTypeEnum.CANCEL);
        } else {
            insapplyOrder.setInsapplyTypeEnum(InsApplyTypeEnum.DELAY);
        }
        insapplyOrder.setApplyUser(systemUser);
        insapplyOrder.setInspectionOrder(inspectionOrder);
        insapplyOrder.setReason(reason);
        insapplyOrder.setEnterprise(inspectionOrder.getEnterprise());
        insapplyOrder.setDictInfo(dictInfoBiz.findModel(StringConverters.null2Long(dictInfoId)));
        dao.add(insapplyOrder);
        inspectionOrder.setInsApplyOrder(insapplyOrder);
        inspectionOrderBiz.update(inspectionOrder);
        return ResultUtil.success();
    }
}
